var City = {
    datalist: {},
    init: function () {
        City.initAllData();
        City.handlerEvent();
    },

    handlerEvent: function () {
        /*省份切换*/
        $('#loc_province').change(function () {
            var currProvince = $('#loc_province').val();
            City.fillOptionWithArr("loc_city", currProvince, null)
        });
        /* 城市切换 */
        $('#loc_city').change(function () {
            var city = $('#loc_city').val();
            console.log("city", city);
            City.fillOptionWithArr("district", city, null)
        });
    },
    /*加载省份数据*/
    initAllData: function () {
        $('#loc_province').empty();
        var url = /*[[@{/common/loadingAllDistrict}]]*/ '/common/loadingAllDistrict';
        Utils.ajaxSubmit(url, {}, function (data) {
            if (data.result == 'success') {
                var list = data.content;
                var cityJsonObj = {};
                $.each(list, function (key, value) {
                    cityJsonObj[value.code] = value.list;
                });
                City.datalist = cityJsonObj;
                Utils.console_log("city", cityJsonObj);
            }
        });
    },
    fillOptionWithArr: function (el_id, parent_code, selected_code) {
        var el = $('#' + el_id);
        el.empty();
        var array = City.datalist[parent_code];
        if (array) {
            var index = 1;
            var selected_index = 0;
            if (array.length == 1) {
                el.append('<option value="">请选择</option>');
            }
            $.each(array, function (k, v) {
                var code = v.code;
                var option = '<option value="' + v.code + '">' + v.name + '</option>';
                if (k == 1) {
                    option = '<option value="' + v.code + '" selected >' + v.name + '</option>';
                }
                if (code == selected_code) {
                    option = '<option value="' + v.code + '" selected >' + v.name + '</option>';
                }
                el.append(option);
                if (code == selected_code) {
                    selected_index = index;
                }
                index++;
            });
            el.attr('selectedIndex', selected_index);
        }
    }
}
$(document).ready(function () {
    City.init();
});
